// 获取当前登录用户信息云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-8g3kxnyv58f85f9b'
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  try {
    // 查询当前登录的用户记录
    const userResult = await db.collection('user').where({
      _openid: openid,
      login_status: 1
    }).orderBy('login_time', 'desc').limit(1).get()
    
    if (userResult.data.length > 0) {
      const currentUser = userResult.data[0]
      
      return {
        success: true,
        isLogin: true,
        userInfo: {
          _id: currentUser._id,
          openid: currentUser.openid,
          phone: currentUser.phone,
          loginTime: currentUser.login_time,
          createTime: currentUser.create_time
        },
        message: '获取用户信息成功'
      }
    } else {
      return {
        success: true,
        isLogin: false,
        userInfo: null,
        message: '用户未登录'
      }
    }
    
  } catch (error) {
    console.error('获取用户信息失败:', error)
    
    return {
      success: false,
      isLogin: false,
      error: 'get_user_failed',
      message: '获取用户信息失败',
      details: error.message
    }
  }
}
